package slidingWindow;

import java.util.HashMap;
import java.util.Map;

//https://leetcode.cn/problems/fruit-into-baskets/
public class l_904 {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> hash = new HashMap<>();

        int n = fruits.length, ans = 0;
        //哈希表维护滑动窗口内水果种类以及数量
        for(int left = 0, right = 0; right < n; ++right) {
            int in = fruits[right];
            hash.put(in, hash.getOrDefault(in, 0) + 1);
            //种类超了就左指针动出窗口删水果
            if(hash.size() > 2) {
                int out = fruits[left++];
                hash.put(out, hash.get(out) - 1);
                if(hash.get(out) == 0) hash.remove(out);
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}
